/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.service.plugins  
 */
package com.apache.uct.service.plugins;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.model.Page;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.ActGive;
import com.apache.uct.common.entity.DataRight;
import com.apache.uct.common.entity.Dept;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.RoleGive;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.DataRightManager;
import com.apache.uct.manager.DeptManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.RoleGiveManager;
import com.apache.uct.manager.RoleManager;
import com.apache.uct.manager.UserManager;

/**
 * description:   权限分配置与查询
 * @author Administrator 创建时间：2016-10-5  
 */
public class UserActsActionPluginImpl implements PluginConnector {

	private UserManager userManager;
	private ProxyManager uctProxyManager;
	private ActManager actManager;
	private ActGiveManager actGiveManager;
	private RoleGiveManager roleGiveManager;
	private RoleManager roleManager;
	private OrgManager orgManager;
	private DeptManager deptManager;
	private DataRightManager dataRightManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo param) throws Exception {
		ResultEntity entity = new ResultEntity();
		entity.setResult("true");
		String method = String.valueOf(param.getParams("method"));
		if ("userRoleData".equalsIgnoreCase(method)) {//拥有的角色
			userRoleData(param, entity);
		} else if ("roleToUser".equalsIgnoreCase(method)) {//分配角色给用户
			String roleId = String.valueOf(param.getParams("roleId"));
			String userId = String.valueOf(param.getParams("userId"));
			String flag = String.valueOf(param.getParams("flag"));
			roleToUser(param, roleId, userId, flag);
			entity.setEntity("true");
		} else if ("userRightRoleData".equalsIgnoreCase(method)) {//继承自角色的权限
			Map<String, Object> map = userRightRoleData(param);
			entity.setEntity(map);
		} else if ("userRightOrgData".equalsIgnoreCase(method)) {//数据权限机构
			net.sf.json.JSONArray jary = userRightOrgData(param);
			entity.setEntity(jary);
		} else if ("userDataGive".equalsIgnoreCase(method)) {//分配数据权限给用户
			userDataGive(param);
			entity.setEntity("true");
		} else if ("userRightAct".equalsIgnoreCase(method)) {//直接分配操作权限
			net.sf.json.JSONArray jary = userRightAct(param);
			entity.setEntity(jary);
		} else if ("userRightAll".equalsIgnoreCase(method)) {
			Map<String, Object> map = userRightAll(param);
			entity.setEntity(map);
		} else if ("userRightDeptData".equalsIgnoreCase(method)) {//数据权限部门
			net.sf.json.JSONArray jary = userRightDeptData(param);
			entity.setEntity(jary);
		} else if ("authorizeAct".equalsIgnoreCase(method)) {//执行权限值分配
			String objId = String.valueOf(param.getParams("objId"));
			String id = String.valueOf(param.getParams("id"));
			String actGiveType = String.valueOf(param.getParams("actGiveType"));
			String flag = String.valueOf(param.getParams("flag"));
			ParamsVo vo = new ParamsVo();
			vo.setParams("flag", flag);
			vo.setParams("actId", id);
			vo.setParams("objId", objId);
			vo.setParams("actGiveType", actGiveType);
			vo.setKey("actGiveExecute");
			String result = String.valueOf(uctProxyManager.doInvoke(vo));
			//			if (Validator.isNotNull(result)) {
			//			}
			entity.setEntity("true");
		}
		entity.setMessage("操作成功");
		return entity;
	}

	private net.sf.json.JSONArray userRightDeptData(ParamsVo param) {
		String parentId = String.valueOf(param.getParams("id"));
		String userId = String.valueOf(param.getParams("userId"));
		if (Validator.isNull(parentId)) {
			parentId = "0";
		}
		ParamsVo<Dept> vo = new ParamsVo<Dept>();
		vo.setParams("fatherId", parentId);
		vo.setParams("userId", userId);
		vo.setParams("dataName", "dept");
		vo.setKey("ByFatherId");

		List<Dept> list = (List<Dept>) deptManager.execute(vo);
		vo.setParams("fatherId", null);
		List<Dept> giveList = (List<Dept>) deptManager.execute(vo);

		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		if (Validator.isEmpty(list))
			return jary;
		for (int i = 0; i < list.size(); i++) {
			Dept ovo = list.get(i);
			net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(ovo);
			if (ovo.getSubCount() != null && ovo.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			String hasGive = hasDept(giveList, ovo.getDeptId()) ? "T" : "F";
			jvo.put("hasGive", hasGive);
			jary.add(jvo);
		}
		return jary;
	}

	private void userDataGive(ParamsVo param) {
		ParamsVo<DataRight> vo = new ParamsVo<DataRight>();
		String objId = String.valueOf(param.getParams("objId"));
		String userId = String.valueOf(param.getParams("userId"));
		String giveType = String.valueOf(param.getParams("giveType"));
		String flag = String.valueOf(param.getParams("flag"));
		DataRight dataRight = new DataRight();
		dataRight.setUserId(userId);
		dataRight.setDataKey(objId);
		dataRight.setDataName(giveType);
		vo.setObj(dataRight);
		if ("add".equals(flag)) {
			dataRightManager.saveInfo(vo);
		} else {
			dataRightManager.deleteInfo(vo);
		}
	}

	private net.sf.json.JSONArray userRightOrgData(ParamsVo param) {
		String parentId = String.valueOf(param.getParams("id"));
		String userId = String.valueOf(param.getParams("userId"));
		Org org = new Org();
		if (Validator.isNull(parentId)) {
			parentId = "0";
		}
		org.setFatherId(parentId);
		ParamsVo<Org> vo = new ParamsVo<Org>();
		vo.setObj(org);
		if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
			String userOrgId = String.valueOf(param.getParams("userOrgId"));//当前登录人机构ID
			if (Validator.isNotNull(userOrgId)) {
				vo.setParams("userOrgId", userOrgId);
				vo.setParams("sysUser", param.getParams("sysFlag"));//是否为系统用户
			}
		}
		List<Org> list = orgManager.getList(vo);
		vo = new ParamsVo<Org>();
		vo.setInfoId(userId);
		vo.setKey("orgsByUserId");
		List<Org> giveList = (List<Org>) orgManager.execute(vo);

		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		if (Validator.isEmpty(list))
			return jary;
		for (int i = 0; i < list.size(); i++) {
			Org ovo = list.get(i);
			net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(ovo);
			if (ovo.getSubCount() != null && ovo.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			String hasGive = hasOrg(giveList, ovo.getOrgId()) ? "T" : "F";
			jvo.put("hasGive", hasGive);
			jary.add(jvo);
		}
		return jary;
	}

	private Map<String, Object> userRightRoleData(ParamsVo param) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = String.valueOf(param.getParams("userId"));
		if (Validator.isNotNull(userId)) {
			ParamsVo vo = new ParamsVo();
			vo.setKey("userActByRoleId");
			vo.setParams("pageSize", Validator.getDefaultStr(String.valueOf(param.getParams("rows")), "20"));
			vo.setParams("pageIndex", Validator.getDefaultStr(String.valueOf(param.getParams("page")), "1"));
			vo.setParams("userId", userId);
			Page actPage = (Page) actManager.execute(vo);
			map.put("total", actPage.getCount());
			map.put("rows", actPage.getPageObjects());
		}
		return map;
	}

	private Map<String, Object> userRightAll(ParamsVo param) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = String.valueOf(param.getParams("userId"));
		if (Validator.isNotNull(userId)) {
			ParamsVo vo = new ParamsVo();
			vo.setKey("userActAll");
			vo.setParams("pageSize", Validator.getDefaultStr(String.valueOf(param.getParams("rows")), "20"));
			vo.setParams("pageIndex", Validator.getDefaultStr(String.valueOf(param.getParams("page")), "1"));
			vo.setParams("userId", userId);
			Page actPage = (Page) actManager.execute(vo);
			map.put("total", actPage.getCount());
			map.put("rows", actPage.getPageObjects());
		}
		return map;
	}

	private void roleToUser(ParamsVo param, String roleId, String userId, String flag) {
		ParamsVo<RoleGive> vo = new ParamsVo<RoleGive>();
		RoleGive roleGive = new RoleGive();
		roleGive.setRoleId(roleId);
		roleGive.setUserId(userId);
		if ("add".equals(flag)) {
			roleGive.setCreateTime(System.currentTimeMillis());
			ParamsVo pvo = new ParamsVo();
			String roleEname = String.valueOf(param.getParams("roleEname"));
			if (Validator.isNull(roleEname)) {
				pvo.setInfoId(roleId);
				Role role = (Role) roleManager.getInfoById(pvo);
				roleGive.setRoleEname(role.getRoleEname());
			} else {
				roleGive.setRoleEname(roleEname);
			}
			pvo.setInfoId(userId);
			User user = (User) userManager.getInfoById(pvo);
			if (!Validator.isEmpty(user)) {
				roleGive.setUserEname(user.getUserEname());
			}
			vo.setObj(roleGive);
			roleGiveManager.saveInfo(vo);
		} else {
			vo.setObj(roleGive);
			roleGiveManager.deleteInfo(vo);
		}
	}

	private void userRoleData(ParamsVo param, ResultEntity entity) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = String.valueOf(param.getParams("userId"));
		if (Validator.isNotNull(userId)) {
			ParamsVo vo = new ParamsVo();
			vo.setKey("userToRole");
			vo.setParams("pageSize", Validator.getDefaultStr(String.valueOf(param.getParams("rows")), "20"));
			vo.setParams("pageIndex", Validator.getDefaultStr(String.valueOf(param.getParams("page")), "1"));
			vo.setParams("userId", userId);
			if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
				String userOrgId = String.valueOf(param.getParams("userOrgId"));//当前登录人机构ID
				if (Validator.isNotNull(userOrgId)) {
					vo.setParams("userOrgId", userOrgId);
					vo.setParams("sysUser", param.getParams("sysFlag"));//是否为系统用户
				}
				ParamsVo<User> uvo = new ParamsVo<User>();
				uvo.setInfoId(userId);
				User user = (User) userManager.getInfoById(uvo);
				if (Validator.isNotNull(user.getOrgId())) {
					if (!user.getOrgId().equals(userOrgId)) {
						vo.setParams("userOrgId", user.getOrgId());
					}
				}
			}
			Page actPage = (Page) roleGiveManager.execute(vo);
			map.put("total", actPage.getCount());
			map.put("rows", actPage.getPageObjects());
			entity.setEntity(map);
		}
	}

	private net.sf.json.JSONArray userRightAct(ParamsVo param) {
		String actId = Validator.getDefaultStr(String.valueOf(param.getParams("id")), "0");
		Act actVo = new Act();
		actVo.setFatherId(actId);
		ParamsVo<Act> vo = new ParamsVo<Act>();
		vo.setObj(actVo);
		List<Act> actList = actManager.getList(vo);
		String userId = String.valueOf(param.getParams("userId"));
		ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
		agVo.setParams("roleId", userId);
		agVo.setParams("giveType", "user");
		agVo.setKey("GiveListByOrgId");
		List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);

		JSONArray jary = new JSONArray();
		for (int i = 0; i < actList.size(); i++) {
			Act avo = actList.get(i);
			JSONObject jvo = JSONObject.fromObject(avo);
			if (avo.getSubCount() != null && avo.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			String hasGive = hasGive(giveList, avo.getActId()) ? "T" : "F";
			jvo.put("hasGive", hasGive);
			jary.add(jvo);
		}
		return jary;
	}

	/**
	 * 判断是否赋予部门数据级权限
	 * @param giveList
	 * @param orgId
	 * @return boolean
	 */
	private boolean hasDept(List<Dept> giveList, String deptId) {
		for (int j = 0; j < giveList.size(); j++) {
			Dept vo = giveList.get(j);
			if (deptId.equals(vo.getDeptId())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断是否赋予机构数据级权限
	 * @param giveList
	 * @param orgId
	 * @return boolean
	 */
	private boolean hasOrg(List<Org> giveList, String orgId) {
		if (Validator.isEmpty(giveList))
			return false;
		for (int j = 0; j < giveList.size(); j++) {
			Org vo = giveList.get(j);
			if (orgId.equals(vo.getOrgId())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断是否包含该权限值
	 * @param giveList 分配的权限值
	 * @param actId 权限值id
	 * @return boolean
	 */
	private boolean hasGive(List<ActGive> giveList, String actId) {
		if (Validator.isEmpty(giveList))
			return false;
		for (int j = 0; j < giveList.size(); j++) {
			ActGive give = giveList.get(j);
			if (actId.equals(give.getActId())) {
				return true;
			}
		}
		return false;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setUctProxyManager(ProxyManager uctProxyManager) {
		this.uctProxyManager = uctProxyManager;
	}

	public void setActManager(ActManager actManager) {
		this.actManager = actManager;
	}

	public void setActGiveManager(ActGiveManager actGiveManager) {
		this.actGiveManager = actGiveManager;
	}

	public void setRoleGiveManager(RoleGiveManager roleGiveManager) {
		this.roleGiveManager = roleGiveManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setDeptManager(DeptManager deptManager) {
		this.deptManager = deptManager;
	}

	public void setDataRightManager(DataRightManager dataRightManager) {
		this.dataRightManager = dataRightManager;
	}

}
